package main

import (
	"net"
	"fmt"
	"github.com/google/gopacket/layers"
	"github.com/google/gopacket"
)

func main() {
	protocol := "tcp"
	netaddr, _ := net.ResolveIPAddr("ip4", "127.0.0.1")
	conn, _ := net.ListenIP("ip4:"+protocol, netaddr)

	buf := make([]byte, 1024)
	numRead, _, _ := conn.ReadFrom(buf)
	//open terminal, send cmd: ping 127.0.0.1
	fmt.Printf("% X\n", buf[:numRead])

	/*我是分割线, gopacket 解析ICMP packet*/
	var icmpv4 layers.ICMPv4
	var iPv4 layers.IPv4
	var tcp layers.TCP
	decoded := []gopacket.LayerType{}
	parser := gopacket.NewDecodingLayerParser(layers.LayerTypeTCP,&tcp)
	parser.DecodeLayers(buf[:numRead], &decoded)
	for _, layerType := range decoded {
		switch layerType {
		case layers.LayerTypeICMPv4:
			fmt.Printf("    icmpv4: typecode->%s,Seq->%x,Checksum->%d,id->%d,Contents:%b", icmpv4.TypeCode.String(), icmpv4.Seq, icmpv4.Checksum, icmpv4.Id, icmpv4.Contents)
		case layers.LayerTypeIPv4:
			fmt.Printf("ipv4 layer protocol->%s, content->%s,ttl->%d,length->%d", iPv4.Protocol.String(), iPv4.Contents, iPv4.TTL, iPv4.Length)
		case layers.LayerTypeTCP:
			fmt.Printf("tcp layer: srcPort->%d,dstPort->%d,Seq->%d,SYN->%d,checksum->%d,contents:%s",tcp.SrcPort,tcp.DstPort,tcp.Seq,tcp.SYN,tcp.Checksum,tcp.Contents)
		}
	}
	/*E3 06 00 50 3B AE 3F 38 00 00 00 00 A0 02 AA AA FE 30 00 00 02 04 FF D7 04 02 08 0A 2C A0 52 5B 00 00 00 00 01 03 03 07
	tcp layer: srcPort->58118,dstPort->80,Seq->1001275192,SYN->%!d(bool=true),checksum->65072,contents:� P;�?8    ����0  ��
	,�R[    
	*/

}
